package com.proidea.gobang;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.Arrays;

public class GobangModel implements Serializable {
	
	public static final String PROP_CHESSMAN = "chessman";	// property name
	
	private PropertyChangeSupport propertySupport; 			// define tool class for property
	private byte[][] chessmanArray = new byte[15][15]; 		// define chess pieces state
	private static GobangModel singletonModel; 				// define singleton for the class's instance 
	
	
	
	public static GobangModel getInstance() {
		if (null == singletonModel) {
			singletonModel = new GobangModel();
		}
		return singletonModel;
	}
	
	public GobangModel() {
		propertySupport = new PropertyChangeSupport(this);	// initialize property tool
		singletonModel = this;
	}
	
	public byte[][] getChessmanArray() {
		return chessmanArray;
	}

	public void setChessmanArray(byte[][] chessmanArray) {
		this.chessmanArray = chessmanArray;
		propertySupport.firePropertyChange(PROP_CHESSMAN, null, chessmanArray);
	}

	/**
	 * add event listener method
	 * @param listener -Event listeners
	 *            
	 */
	public void addPropertyChangeListener(PropertyChangeListener listener) {
		propertySupport.addPropertyChangeListener(listener); 	// add event listeners
	}

	/**
	 * remove event listener method
	 * @param listener -Event listeners
	 *            
	 */
	public void removePropertyChangeListener(PropertyChangeListener listener) {
		propertySupport.removePropertyChangeListener(listener); // add event listeners
	}
	
	/**
	 * update chessman array 
	 * @param chessmanArray
	 */
	public synchronized void updateChessmanArray(byte[][] chessmanArray) {
		this.chessmanArray = chessmanArray;
	}
	
	/**
	 * copy the chessman array
	 * @return - chessmanArray[][]
	 */
	byte[][] getChessmanArrayCopy() {
		byte[][] newArray = new byte[15][15]; 
		for (int i = 0; i < newArray.length; i++) {
			// copy chessman array
			newArray[i] = Arrays.copyOf(chessmanArray[i], newArray[i].length);
		}
		return newArray;
	}
}
